package com.cw.jeeyt.service.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author Qdlakes
 * @version createTime：2018年7月12日 下午5:03:05 类说明:
 */
public class ZipUtil {

    /**
     * 压缩数据
     *
     * @param inString 待压缩数据
     * @param charSet 字符集
     * @return
     */
    public static String GZipString(String inString, String charSet) {

        if (inString == null) {
            return null;
        }
        if (charSet == null) {
            charSet = "UTF-8";
        }
        try {
            ByteArrayOutputStream bos = null;
            GZIPOutputStream os = null;
            String result = "GZIP:";
            byte[] bs = null;
            try {
                bos = new ByteArrayOutputStream();
                os = new GZIPOutputStream(bos);
                os.write(inString.getBytes());
                os.close();
                bos.close();
                bs = bos.toByteArray();
                result = result + new String(bs, charSet);
                return result;
            } finally {
                bs = null;
                bos = null;
                os = null;
            }
        } catch (Exception ex) {
            return inString;
        }

    }

    /**
     * 根据长度确定是否压缩数据
     *
     * @param inString 压缩入参
     * @param charSet 字符集
     * @param length 压缩字段起始长度
     * @return
     */
    public static String GZipStringByLength(String inString, String charSet, Integer length) {
        if (inString == null) {
            return null;
        }
        if (inString.getBytes().length >= length) {
            return GZipString(inString, charSet);
        } else {
            return inString;
        }

    }

    /**
     * 解压数据
     *
     * @param inString 加压字符串
     * @param charSet 字符集
     * @return
     */
    public static String UnGZipString(String inString, String charSet) {
        if (inString == null) {
            return null;
        }

        if (!inString.startsWith("GZIP:")) {
            return inString;
        }
        inString = inString.replace("GZIP:", "");
        ByteArrayInputStream bis = null;
        ByteArrayOutputStream bos = null;
        GZIPInputStream is = null;
        byte[] buf = null;
        try {
            bis = new ByteArrayInputStream(inString.getBytes(charSet));
            bos = new ByteArrayOutputStream();
            is = new GZIPInputStream(bis);
            buf = new byte[1024];
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            is.close();
            bis.close();
            bos.close();
            return new String(bos.toByteArray(), "UTF-8");
        } catch (Exception ex) {
            return inString;
        } finally {
            bis = null;
            bos = null;
            is = null;
            buf = null;
        }

    }

}
